<template>
  <div class="flex flex-col h-screen">
    <component
      :is="
        liveDataStore.roomData?.screenType === 1
          ? PlayerLandscape
          : PlayerPortrait
      "
      :video-url="
        liveDataStore.roomData.realTime?.pullWebRTCUrl
          ? liveDataStore.roomData.realTime?.pullWebRTCUrl
          : liveDataStore.roomData?.streamAddress
      "
      :video-poster="liveDataStore.roomData?.cover"
      :is-portrait="liveDataStore.roomData?.screenType === 1"
      :show-time="liveDataStore.roomData.hasShowTime == 1"
      class="flex-shrink-0"
      @update="updateProgress"
    />
    <OnlineCount
      v-if="liveDataStore.roomData.openLivePeopleNum === 1"
      :count="liveDataStore.roomWatchData?.onlineCount || 0"
      class="absolute top-4 right-4 z-20"
    />
    <MemberId
      :member-id="userStore.user?.buyerUserId"
      class="absolute top-4 left-0 z-20"
    />
    <component
      :is="
        liveDataStore.roomData?.screenType === 1
          ? InteractionLandscape
          : InteractionPortrait
      "
      v-if="
        liveDataStore.roomData?.openInteraction === 1 ||
        liveDataStore.roomData?.question.openQuestion === 1
      "
    />
    <SignIn
      v-if="liveDataStore.roomData?.sign.openSignIn && signInStore?.isVisible"
      :remaining-time="liveDataStore.roomData.sign.signInTime * 60"
      :loading="signInStore?.loading"
      @success="signInStore.handleSignin(liveDataStore)"
      @timeout="signInStore.setIsVisible(false)"
      class="z-50"
    />
    <audio ref="audioRef" src="./data/signin.mp3" muted></audio>
    <InteractionMenu
      v-if="!playerStore.isFullScreen"
      class="fixed bottom-20 right-1 z-50"
      :style-mode="liveDataStore.roomData.screenType ? 'cover' : ''"
    ></InteractionMenu>
    <WeatherCover :imgSrc="liveDataStore.roomData.transitionImg" />
  </div>
</template>

<script setup lang="ts">
import InteractionPortrait from "./components/InteractionPortrait.vue";
import InteractionLandscape from "./components/InteractionLandscape.vue";
import PlayerLandscape from "./components/PlayerLandscape.vue";
import PlayerPortrait from "./components/PlayerPortrait.vue";
import SignIn from "@/views/LiveNew/components/SignIn.vue";
import OnlineCount from "./components/OnlineCount.vue";
import MemberId from "@/components/MemberId.vue";
import useLiveDataStore from "@/views/LiveNew/stores/LiveDataStore";
import { useSignInStore } from "@/views/LiveNew/stores/SignInStore";
import { usePlayerStore } from "@/store/usePlayer";
import { useUserStore } from "@/store/useUserStore";
import { useAudioAutoPlay } from "@/utils/audioAutoPlay";
import { watch, onMounted, onUnmounted } from "vue";
import { useRewardStore } from "@/views/LiveNew/stores/RewardStore";
import { useRedPacketStore } from "@/views/LiveNew/stores/RedPacketStore";
import { useLiveControl } from "@/views/LiveNew/stores/LiveControl";
import { useQuestionStore } from "@/views/LiveNew/stores/QuestionStore";
import InteractionMenu from "./components/interactionMenu.vue";
import { updateLiveOnline } from "./LiveNewApi";
import router from "@/router";
import { useRoute } from "vue-router";
import { useOnlineTimer } from "@/views/LiveNew/stores/OnlineTimer";
import WeatherCover from "@/components/WeatherCover.vue";
import { useLocationParams } from "@/store/useLocationStore";
const liveDataStore = useLiveDataStore();
const signInStore = useSignInStore();
const playerStore = usePlayerStore();
const userStore = useUserStore();
const redPacketStore = useRedPacketStore();
const rewardStore = useRewardStore();
const liveControlStore = useLiveControl();
const onlineTimerStore = useOnlineTimer();
const { audioRef, playAudio, initAudioAutoPlay, cleanupAudioAutoPlay } =
  useAudioAutoPlay();

const userId = userStore.user.buyerUserId;
const storageKey = `LiveProgress_${userId}_${liveDataStore.roomWatchData?.watchRecordId}`;
playerStore.setPlayerStorageKey(storageKey);

let audioTimer: NodeJS.Timeout | null = null;
let onlineTimer: NodeJS.Timeout | null = null;

const updateProgress = (progress: number) => {
  playerStore.updateMaxProgress(progress);
  // console.log("progress", playerStore.realProgress);
};

const initSignInWatcher = () => {
  signInStore.initWatcher(liveDataStore, playerStore);
};

const initRedPacketWatcher = () => {
  redPacketStore.initWatcher(liveDataStore, playerStore);
};

const initRewardWatcher = () => {
  rewardStore.initWatcher(liveDataStore, redPacketStore, onlineTimerStore);
};

initSignInWatcher();
initRedPacketWatcher();
initRewardWatcher();
const questionStore = useQuestionStore();
liveControlStore.initWatcher(liveDataStore, questionStore, signInStore);
// 监听签到弹窗显示状态
watch(
  () => signInStore.isVisible,
  isVisible => {
    if (isVisible && liveDataStore.roomData?.sign.signInSound == 1) {
      playAudio();
      audioTimer && clearInterval(audioTimer);
      audioTimer = setInterval(() => playAudio(), 5000);
    } else {
      if (audioRef.value) {
        audioRef.value.pause();
        audioRef.value.load();
      }
      if (audioTimer) {
        clearInterval(audioTimer);
        audioTimer = null;
      }
    }
    if (isVisible) {
      playerStore.setFullScreen(false);
    }
  }
);
watch(
  () => questionStore.isVisible,
  isVisible => {
    if (isVisible) {
      playerStore.setFullScreen(false);
    }
  }
);

const route = useRoute();
watch(
  () => liveControlStore.isLiveEnd,
  isLiveEnd => {
    if (isLiveEnd) {
      liveControlStore.endWatcher();
      router.replace({
        name: "LiveEnd",
        query: {
          ...route.query,
          transcribeOpenType: liveDataStore.roomData.transcribe.openType,
          roomTitle: liveDataStore.roomData.title
        }
      });
    }
  }
);

onMounted(() => {
  initAudioAutoPlay();
  onlineTimerStore.startOnlineUpdater(liveDataStore);
});

onUnmounted(() => {
  // 清理音频相关
  if (audioTimer) {
    audioRef.value?.pause();
    audioRef.value?.load();
    clearInterval(audioTimer);
  }
  cleanupAudioAutoPlay();
  onlineTimerStore.endOnlineUpdater();
  liveControlStore.endWatcher();
});
document.title =
  liveDataStore.roomData.shareVipTitle ||
  liveDataStore.roomData.title ||
  liveDataStore.roomData.shopName;
</script>
